#include "command.h"

/* return -1 for failure */
int remove_file(const char *file) {
	if (unlink(file) == -1) {
		fprintf(stderr, "rm error: remove_file-->unlink\n");
		return -1;
	}
	return 0;
}

/* return -1 for failure */
int remove_directory(const char *path)
{
	struct dirent *entry; // store the read directory entry

	/* open the directory */
	DIR *dir = opendir(path);
	if (!dir) {
		fprintf(stderr, "rm error: remove_directory-->opendir\n");
		closedir(dir);
		return -1;
	}

	/* remove directory and files in it */
	while ((entry = readdir(dir)) != NULL) {
		// ignore the directory "." and ".."
		if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
			continue;

		char full_path[FILEPATH_SIZE];
		snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
		
		if (entry->d_type == DT_DIR) {
			// recursively remove directory
			if (remove_directory(full_path) == -1) {
				fprintf(stderr, "rm error: remove_directory-->recursively remove\n");
				closedir(dir);
				return -1;
			}
		} else {
			// remove the file
			if (remove_file(full_path) == -1) {
				fprintf(stderr, "rm error: remove_directory-->remove_file\n");
				closedir(dir);
				return -1;
			}
		}
	}

	closedir(dir);

	// remove the empty directory
	if (rmdir(path) == -1) {
		fprintf(stderr, "rm error: remove_directory-->rmdir\n");
		return -1;
	}

	return 0;
}

int _rm(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc < 2) {
		fprintf(stderr, "Usage: rm file or [-r] dir ...\n");
		return -1;
	}

	/* parse the cmd-line parameters */
	int recursive_rm_dir = 0;
	const char *optfmt = "r";
	int opt;
	while ((opt = getopt(argc, argv, optfmt)) != -1) {
		switch (opt) {
			case 'r':
				recursive_rm_dir = 1;
				break;
			default:
				fprintf(stderr, "Usage: rm file or [-r] dir ...\n");
				break;
		}
	}

	if (!argv[optind]) {
		fprintf(stderr, "Usage: rm file or [-r] dir ...\n");
		return -1;
	}

	/* remove file or directory */
	const char *file;
	for (int i = optind; i < argc; i++) {
		file = argv[i];
		if (recursive_rm_dir == 1) {
			if (remove_directory(file) == -1) {
				fprintf(stderr, "rm error: remove_directory\n");
				return -1;
			}
		} else {
			if (remove_file(file) == -1) {
				fprintf(stderr, "rm error: remove_file\n");
				return -1;
			}
		}
	}

	return 0;
}
